package com.example.chamberlainserver.controller;

import com.example.chamberlainserver.Entry.Department;
import com.example.chamberlainserver.Service.DepartmentService;
import com.example.chamberlainserver.dto.PageResult;
import com.example.chamberlainserver.Vo.Response.ApiResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 部门管理控制器
 */
@RestController
@RequestMapping("/department")
public class DepartmentController {

    private static final Logger logger = LoggerFactory.getLogger(DepartmentController.class);

    @Autowired
    private DepartmentService departmentService;

    /**
     * 获取所有部门
     */
    @GetMapping("/list")
    public ResponseEntity<ApiResponse> getAllDepartments() {
        List<Department> departments = departmentService.getAllDepartments();
        return ResponseEntity.ok(ApiResponse.success(departments));
    }

    /**
     * 分页获取部门列表
     */
    @GetMapping("/page")
    public ResponseEntity<PageResult<Department>> getDepartmentsByPage(
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "10") int pageSize) {
        List<Department> departments = departmentService.getAllDepartments();
        
        // 简单分页处理
        Long total = (long) departments.size();
        int start = (pageNum - 1) * pageSize;
        int end = Math.min(start + pageSize, departments.size());
        
        List<Department> pageData = departments.subList(start < departments.size() ? start : 0, end);
        
        PageResult<Department> pageResult = new PageResult<>(pageNum, pageSize, total, pageData);
        
        return ResponseEntity.ok(pageResult);
    }

    /**
     * 根据ID获取部门
     */
    @GetMapping("/{id}")
    public ResponseEntity<ApiResponse> getDepartmentById(@PathVariable Integer id) {
        Department department = departmentService.getDepartmentById(id);
        if (department != null) {
            return ResponseEntity.ok(ApiResponse.success(department));
        } else {
            return ResponseEntity.status(HttpStatus.NOT_FOUND)
                    .body(ApiResponse.error("部门不存在"));
        }
    }

    /**
     * 添加部门
     */
    @PostMapping
    public ResponseEntity<ApiResponse<Department>> addDepartment(@RequestBody Department department) {
        // 验证部门代码和名称唯一性
        if (!departmentService.isDepartmentCodeUnique(department.getCode(), null)) {
            return ResponseEntity.badRequest()
                    .body(ApiResponse.error("部门代码已存在"));
        }
        
        if (!departmentService.isDepartmentNameUnique(department.getName(), null)) {
            return ResponseEntity.badRequest()
                    .body(ApiResponse.error("部门名称已存在"));
        }
        
        boolean success = departmentService.addDepartment(department);
        if (success) {
            return ResponseEntity.ok(ApiResponse.success("部门添加成功", department));
        } else {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(ApiResponse.error("部门添加失败"));
        }
    }

    /**
     * 更新部门
     */
    @PutMapping("/{id}")
    public ResponseEntity<ApiResponse<Department>> updateDepartment(
            @PathVariable Integer id,
            @RequestBody Department department) {
        
        logger.info("开始更新部门，ID: {}, 请求数据: {}", id, department);
        
        Department existingDept = departmentService.getDepartmentById(id);
        if (existingDept == null) {
            logger.warn("部门不存在，ID: {}", id);
            return ResponseEntity.status(HttpStatus.NOT_FOUND)
                    .body(ApiResponse.error("部门不存在"));
        }
        
        logger.info("找到现有部门: {}", existingDept);
        
        // 验证部门代码和名称唯一性
        if (!departmentService.isDepartmentCodeUnique(department.getCode(), id)) {
            logger.warn("部门代码已存在: {}, 排除ID: {}", department.getCode(), id);
            return ResponseEntity.badRequest()
                    .body(ApiResponse.error("部门代码已存在"));
        }
        
        if (!departmentService.isDepartmentNameUnique(department.getName(), id)) {
            logger.warn("部门名称已存在: {}, 排除ID: {}", department.getName(), id);
            return ResponseEntity.badRequest()
                    .body(ApiResponse.error("部门名称已存在"));
        }
        
        logger.info("验证通过，准备更新部门数据");
        department.setId(id);
        logger.info("设置部门ID后的数据: {}", department);
        
        boolean success = departmentService.updateDepartment(department);
        logger.info("部门更新结果: {}", success);
        
        if (success) {
            logger.info("部门更新成功，ID: {}", id);
            return ResponseEntity.ok(ApiResponse.success("部门更新成功", department));
        } else {
            logger.error("部门更新失败，ID: {}", id);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(ApiResponse.error("部门更新失败"));
        }
    }

    /**
     * 删除部门
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<ApiResponse> deleteDepartment(@PathVariable Integer id) {
        // 检查部门是否存在
        Department department = departmentService.getDepartmentById(id);
        if (department == null) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND)
                    .body(ApiResponse.error("部门不存在"));
        }
        
        // 检查部门下是否有用户
        List<Integer> userIds = departmentService.getUserIdsByDepartmentId(id);
        if (userIds != null && !userIds.isEmpty()) {
            return ResponseEntity.badRequest()
                    .body(ApiResponse.error("部门下存在用户，无法删除"));
        }
        
        boolean success = departmentService.deleteDepartment(id);
        if (success) {
            return ResponseEntity.ok(ApiResponse.success(null, "部门删除成功"));
        } else {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(ApiResponse.error("部门删除失败"));
        }
    }
    
    /**
     * 检查部门代码是否唯一
     */
    @GetMapping("/check-code")
    public ResponseEntity<ApiResponse> checkCodeUnique(
            @RequestParam String code,
            @RequestParam(required = false) Integer excludeId) {
        
        boolean isUnique = departmentService.isDepartmentCodeUnique(code, excludeId);
        Map<String, Boolean> result = new HashMap<>();
        result.put("unique", isUnique);
        
        return ResponseEntity.ok(ApiResponse.success(result));
    }
    
    /**
     * 检查部门名称是否唯一
     */
    @GetMapping("/check-name")
    public ResponseEntity<ApiResponse> checkNameUnique(
            @RequestParam String name,
            @RequestParam(required = false) Integer excludeId) {
        
        boolean isUnique = departmentService.isDepartmentNameUnique(name, excludeId);
        Map<String, Boolean> result = new HashMap<>();
        result.put("unique", isUnique);
        
        return ResponseEntity.ok(ApiResponse.success(result));
    }
}